package com.xiaoye.qbproject.controller.qbzyk;

/**
 * @author : ChenYao
 * @version : 1.0
 * @description :
 * @create : 2024-12-27 3:01
 */

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xiaoye.qbproject.config.XiaoYeConfig;
import com.xiaoye.qbproject.controller.base.BaseController;
import com.xiaoye.qbproject.domain.AjaxResult;
import com.xiaoye.qbproject.domain.ZbAttr;
import com.xiaoye.qbproject.domain.ZbInfo;
import com.xiaoye.qbproject.page.TableDataInfo;
import com.xiaoye.qbproject.redis.RedisCache;
import com.xiaoye.qbproject.service.ZbInfoService;
import com.xiaoye.qbproject.util.poi.ExcelUtil;
import com.xiaoye.qbproject.util.poi.ZbInfoExcelUtil;
import com.xiaoye.qbproject.util.poi.ZbInfoV2ExcelUtil;
import com.xiaoye.qbproject.util.uuid.UUID;
import com.xiaoye.qbproject.vo.ZbAttrImportVo;
import com.xiaoye.qbproject.vo.ZbImportV2Vo;
import com.xiaoye.qbproject.vo.ZbImportVo;
import com.xiaoye.qbproject.vo.ZbInfoVo;
import com.xiaoye.qbproject.vo.dropDown.ZbInfoDropDownVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/***
 * @description: 装备信息
 * @author: ChenYao
 * @ceateDate: 2024-12-27 3:10
 */
@Slf4j
@RestController
@RequestMapping("/zbInfo")
public class ZbInfoController extends BaseController {
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ZbInfoService zbInfoService;

    // 这里可以添加具体的接口方法，例如查询、新增、更新等操作
    // 示例：获取基本信息列表
    @RequestMapping("/list")
    public TableDataInfo getZbInfoList(ZbInfoVo zbInfoVo) {
        startPage();
        List<ZbInfo> list = zbInfoService.getZbInfoList(zbInfoVo);
        for (ZbInfo zbInfo : list) {
            String feature = zbInfo.getFeature();
            List<ZbAttr> attrs = zbInfo.getAttrs();
            if (StringUtils.isNotBlank(feature) || CollectionUtils.isEmpty(attrs)) {
                continue;
            }
            // 把 attrs 转字符串
            StringBuilder sb = new StringBuilder();
            List<ZbAttr> zbAttr1 = JSON.parseArray(JSON.toJSONString(attrs), ZbAttr.class);
            for (ZbAttr zbAttr : zbAttr1) {
                List<String> zbAttrAttrs = zbAttr.getAttrs();
                for (String attr : zbAttrAttrs) {
                    sb.append(zbAttr.getAttrName()).append(":").append(attr).append("\n");
                }
            }
            String attrStr = sb.toString();
            zbInfo.setFeature(attrStr);
        }
        return getDataTable(list);
    }

    @GetMapping("/{id}")
    public AjaxResult getZbInfoById(@PathVariable String id) {
        ZbInfo zbInfo = zbInfoService.getZbInfo(id);
        return AjaxResult.success(zbInfo);
    }

    /**
     * @description: 查询装备下拉列表信息
     * @author: ChenYao
     * @return: com.xiaoye.qbproject.domain.AjaxResult
     * @ceateDate: 2025-01-02 14:08
     */

    @GetMapping("/dropDown")
    public AjaxResult dropDown() {
        List<ZbInfoDropDownVO> dropDownVOS = zbInfoService.dropDown();
        return AjaxResult.success(dropDownVOS);
    }

    /**
     * @param subjectId
     * @description: 查询装备下拉列表信息(排除和专题已关联的)
     * @author: ChenYao
     * @return: com.xiaoye.qbproject.domain.AjaxResult
     * @ceateDate: 2025/2/11 下午3:59
     */

    @GetMapping("/excludeRelateToDropDown")
    public AjaxResult excludeRelateToDropDown(String subjectId) {
        List<ZbInfoDropDownVO> dropDownVOS = zbInfoService.excludeRelateToDropDown(subjectId);
        return AjaxResult.success(dropDownVOS);
    }

    @PostMapping()
    public AjaxResult saveZbInfo(@RequestBody ZbInfo zbInfo) {
        zbInfoService.delCache();
        return toAjax(zbInfoService.save(zbInfo));
    }

    @PutMapping
    public AjaxResult updateZbInfo(@RequestBody ZbInfo zbInfo) {
        zbInfoService.delCache();
        return toAjax(zbInfoService.updateById(zbInfo));
    }

    @DeleteMapping("/{id}")
    public AjaxResult deleteZbInfo(@PathVariable Long id) {
        zbInfoService.delCache();
        return toAjax(zbInfoService.removeById(id));
    }

    /**
     * @param file
     * @description: 导入装备性能参数信息, 性能参数
     * @author: ChenYao
     * @return: com.xiaoye.qbproject.domain.AjaxResult
     * @ceateDate: 2024-12-27 13:40
     */

    @PostMapping(value = "/importZbInfo")
    public AjaxResult importZbInfo(@RequestParam("file") MultipartFile file) {
        // 获取文件名
        String filename = file.getOriginalFilename();
        File file1 = new File(XiaoYeConfig.getImportPath() + File.separator + filename);
        file1.getParentFile().mkdirs();
        try {
            file.transferTo(file1);
            // 请求中获取上传的文件
            ZbInfoExcelUtil excelUtil = new ZbInfoExcelUtil();
            Map<String, Object> sheetZbImportVoMap = excelUtil.readExcelMuchSheetToObj(file1.getPath());
            //List<ZbImportVo> result = excelUtil.readExcelToObj(file1.getPath());
            sheetZbImportVoMap.forEach((key, value) -> {
                List<ZbImportVo> zbImportVos = (List<ZbImportVo>) value;
                zbInfoService.saveZbAndTypeAndModules(zbImportVos, key);
            });
            //zbInfoService.saveZbAndTypeAndModules(result);
            return success("导入成功");

        } catch (IOException e) {
            e.getLocalizedMessage();
            log.error("导入失败", e.getLocalizedMessage());
            return AjaxResult.error("上传失败");
        }
    }

    /**
     * @param file
     * @description: 装备数据导入
     * @author: ChenYao
     * @return: com.xiaoye.qbproject.domain.AjaxResult
     * @ceateDate: 2024-12-31 14:12
     */

    @PostMapping("importZbAttrInfo")
    public AjaxResult importZbAttrInfo(@RequestParam("file") MultipartFile file) throws IOException {
        ExcelUtil<ZbAttrImportVo> util = new ExcelUtil<ZbAttrImportVo>(ZbAttrImportVo.class);
        List<ZbAttrImportVo> zbAttrImportVos = util.importExcel(file.getInputStream());
        zbInfoService.importZbAttrInfo(zbAttrImportVos);
        return success();
    }

    /**
     * @description: 支持情报资源按需导出，且导出的文件格式需符合OWL标准的资源描述规范
     * @author: ChenYao
     * @return: com.xiaoye.qbproject.domain.AjaxResult
     * @ceateDate: 2024-12-28 1:56
     */

    @PostMapping("exportZbInfo")
    public AjaxResult exportZbInfo() {
        return success();
    }

    /**
     * @param ids
     * @param response
     * @description: 导出OWL文件
     * @author: ChenYao
     * @return: void
     * @ceateDate: 2025-01-03 16:02
     */

    @PostMapping(value = "/exportOwl", produces = MediaType.TEXT_XML_VALUE)
    public void exportOwl(@RequestBody String[] ids, HttpServletResponse response) {
        // 设置响应头信息
        response.setHeader("Content-Disposition", "attachment; filename=\"ZB_INFO_" + UUID.fastUUID() + ".owl\"");
        response.setHeader("Content-Type", "application/xml;charset=UTF-8");
        log.info("开始导出数据...:{}", ids);
        // 调用服务方法导出数据
        zbInfoService.exportOwl(ids, response);

    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        String encode = URLEncoder.encode("果管理];功能:[校验];", "UTF-8");
        System.out.println();
        encode = URLDecoder.decode(encode, "UTF-8");
        System.out.println(encode);
    }

    @PostMapping("importZbInfoV2")
    public AjaxResult importZbInfoV2(@RequestParam("file") MultipartFile file) {
        // 获取文件名
        String filename = file.getOriginalFilename();
        File file1 = new File(XiaoYeConfig.getImportPath() + File.separator + filename);
        file1.getParentFile().mkdirs();
        try {
            file.transferTo(file1);
            // 请求中获取上传的文件
            ZbInfoV2ExcelUtil excelUtil = new ZbInfoV2ExcelUtil();
            Map<String, Object> sheetZbImportVoMap = excelUtil.readExcelMuchSheetToObj(file1.getPath());
            sheetZbImportVoMap.forEach((key, value) -> {
                List<ZbImportV2Vo> zbImportVos = (List<ZbImportV2Vo>) value;
                zbInfoService.saveZbInfoV2(zbImportVos, key);
            });
            return success("导入成功");

        } catch (IOException e) {
            e.getLocalizedMessage();
            log.error("导入失败:{}", e.getLocalizedMessage());
            return AjaxResult.error("上传失败");
        }
    }

}
